<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col
        :span="4"
        :xs="24"
      >
        <div class="head-container">
          <el-input
            v-model="deptName"
            clearable
            :placeholder="$t('system.userManagement.deptNamePlaceholder')"
            prefix-icon="ele-Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="treeRef"
            :data="deptOptions"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :props="defaultProps"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col
        :span="20"
        :xs="24"
      >
        <el-form
          v-show="showSearch"
          ref="queryFormRef"
          :inline="true"
          :model="queryParams"
          label-width="68px"
        >
          <el-form-item
            :label="$t('system.userManagement.userName')"
            prop="userName"
          >
            <el-input
              v-model="queryParams.userName"
              clearable
              :placeholder="$t('system.userManagement.userNamePlaceholder')"
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item
            :label="$t('system.userManagement.nickName')"
            prop="nickName"
          >
            <el-input
              v-model="queryParams.nickName"
              :placeholder="$t('system.userManagement.nickNamePlaceholder')"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item
            label-width="110px"
            :label="$t('system.userManagement.phoneNumber')"
            prop="phonenumber"
          >
            <el-input
              v-model="queryParams.phonenumber"
              clearable
              :placeholder="$t('system.userManagement.phoneNumberPlaceholder')"
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item
            :label="$t('system.userManagement.email')"
            prop="email"
          >
            <el-input
              v-model="queryParams.email"
              :placeholder="$t('system.userManagement.emailPlaceholder')"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item
            :label="$t('system.userManagement.status')"
            prop="status"
          >
            <el-select
              v-model="queryParams.status"
              clearable
              :placeholder="$t('system.userManagement.statusPlaceholder')"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label-width="110px"
            :label="$t('system.userManagement.createTime')"
          >
            <el-date-picker
              v-model="dateRange"
              :end-placeholder="$t('system.userManagement.endTimePlaceholder')"
              range-separator="-"
              :start-placeholder="$t('system.userManagement.startTimePlaceholder')"
              style="width: 240px"
              type="daterange"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item :label="$t('system.userManagement.userRoles')">
            <el-select
              style="width: 240px"
              v-model="queryParams.roleIds"
              multiple
              clearable
              collapse-tags
              :placeholder="$t('formI18n.all.pleaseEnter')"
            >
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              icon="ele-Search"
              type="primary"
              @click="handleQuery"
            >
              {{ $t("formI18n.all.search") }}
            </el-button>
            <el-button
              icon="ele-Refresh"
              @click="resetQuery"
            >
              {{ $t("formI18n.all.reset") }}
            </el-button>
          </el-form-item>
        </el-form>

        <el-row
          :gutter="10"
          class="mb8"
        >
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:add']"
              icon="ele-Plus"
              plain
              type="primary"
              @click="handleAdd"
            >
              {{ $t("formI18n.all.add") }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:edit']"
              :disabled="single"
              icon="ele-Edit"
              plain
              type="success"
              @click="handleUpdate"
            >
              {{ $t("formI18n.all.modify") }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:remove']"
              :disabled="multiple"
              icon="ele-Delete"
              plain
              type="danger"
              @click="handleDelete"
            >
              {{ $t("formI18n.all.delete") }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:import']"
              icon="ele-Upload"
              plain
              type="info"
              @click="handleImport"
            >
              {{ $t("formI18n.all.import") }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:export']"
              :loading="exportLoading"
              icon="ele-Download"
              plain
              type="warning"
              @click="handleExport"
            >
              {{ $t("system.userManagement.export") }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:syncCpWx']"
              icon="ele-Link"
              plain
              @click="() => $refs.syncCpWxRef!.show()"
            >
              {{ $t("system.userManagement.syncCpWxAccount") }}
            </el-button>
          </el-col>
          <right-toolbar
            :columns="columns"
            v-model:show-search="showSearch"
            @query-table="getList"
          />
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            align="center"
            type="selection"
            width="50"
          />
          <el-table-column
            v-if="columns[0].visible"
            align="center"
            :label="$t('system.userManagement.userNumber')"
            prop="id"
          />
          <el-table-column
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
            align="center"
            :label="$t('system.userManagement.userName')"
            prop="userName"
          />
          <el-table-column
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            align="center"
            :label="$t('system.userManagement.nickName')"
            prop="nickName"
          />
          <el-table-column
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
            align="center"
            :label="$t('system.userManagement.dept')"
            prop="dept.deptName"
          />
          <el-table-column
            v-if="columns[4].visible"
            align="center"
            :label="$t('system.userManagement.phoneNumber')"
            prop="phonenumber"
            width="120"
          />
          <el-table-column
            v-if="columns[5].visible"
            align="center"
            :label="$t('system.userManagement.email')"
            prop="email"
            width="120"
          />
          <el-table-column
            v-if="columns[6].visible"
            align="center"
            :label="$t('system.userManagement.status')"
          >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns[7].visible"
            align="center"
            :label="$t('system.userManagement.createTime')"
            prop="createTime"
            width="180"
          >
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columns[8].visible"
            align="center"
            :label="$t('system.userManagement.wxMpAccount')"
            prop="wxMpAccount"
            width="180"
          >
            <template #default="scope">
              <span>{{ scope.row.wxMpName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            class-name="small-padding fixed-width"
            :label="$t('system.userManagement.operation')"
            width="170"
          >
            <template #default="scope">
              <el-tooltip
                :content="$t('formI18n.all.modify')"
                placement="top"
                v-if="scope.row.id !== 1"
              >
                <el-button
                  link
                  type="primary"
                  icon="ele-Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:user:edit']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                :content="$t('formI18n.all.delete')"
                placement="top"
                v-if="scope.row.id !== 1"
              >
                <el-button
                  link
                  type="danger"
                  icon="ele-Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:user:remove']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                :content="$t('system.userManagement.resetPassword')"
                placement="top"
                v-if="scope.row.id !== 1"
              >
                <el-button
                  link
                  type="primary"
                  icon="ele-Key"
                  @click="handleResetPwd(scope.row)"
                  v-hasPermi="['system:user:resetPwd']"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                :content="$t('system.userManagement.divideDept')"
                placement="top"
                v-if="scope.row.id !== 1"
              >
                <el-button
                  link
                  type="primary"
                  icon="ele-CircleCheck"
                  @click="handleAuthRole(scope.row)"
                  v-hasPermi="['system:user:roleauth']"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          v-model:limit="queryParams.size"
          v-model:page="queryParams.current"
          :total="total"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      append-to-body
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="$t('system.userManagement.nickName')"
              prop="nickName"
            >
              <el-input
                v-model="form.nickName"
                maxlength="30"
                :placeholder="$t('system.userManagement.nickNamePlaceholder')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label-width="110px"
              :label="$t('system.userManagement.belongingDept')"
              prop="deptId"
            >
              <el-tree-select
                @change="handleDeptChange"
                check-strictly
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                :placeholder="$t('system.userManagement.belongingDeptPlaceholder')"
                default-expand-all
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              :label="$t('system.userManagement.phoneNumber')"
              prop="phonenumber"
            >
              <el-input
                v-model="form.phonenumber"
                maxlength="11"
                :placeholder="$t('system.userManagement.phoneNumberPlaceholder')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('system.userManagement.email')"
              prop="email"
            >
              <el-input
                v-model="form.email"
                maxlength="50"
                :placeholder="$t('system.userManagement.emailPlaceholder')"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="form.id == undefined"
              :label="$t('system.userManagement.userName')"
              prop="userName"
            >
              <el-input
                v-model="form.userName"
                maxlength="30"
                :placeholder="$t('system.userManagement.userNamePlaceholder')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.id == undefined"
              :label="$t('system.userManagement.password')"
              prop="password"
            >
              <el-input
                v-model="form.password"
                maxlength="20"
                :placeholder="$t('system.userManagement.passwordPlaceholder')"
                type="password"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('system.userManagement.userSex')">
              <el-select
                v-model="form.sex"
                :placeholder="$t('formI18n.all.pleaseEnter')"
              >
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('system.userManagement.status')">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :value="dict.dictValue"
                >
                  {{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('system.userManagement.post')">
              <el-select
                v-model="form.postIds"
                multiple
                :placeholder="$t('formI18n.all.pleaseEnter')"
              >
                <el-option
                  v-for="item in postOptions"
                  :key="item.id"
                  :label="item.postShowName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('system.userManagement.userRoles')">
              <el-select
                v-model="form.roleIds"
                multiple
                :placeholder="$t('formI18n.all.pleaseEnter')"
                @change="
                  () => {
                    $forceUpdate();
                  }
                "
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :disabled="item.status == 1"
                  :label="item.roleName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('system.userManagement.remark')">
              <el-input
                v-model="form.remark"
                :placeholder="$t('formI18n.all.pleaseEnter')"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="form.id">
        <user-auth-info :user-id="form.id" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitForm"
          >
            {{ $t("formI18n.all.confirm") }}
          </el-button>
          <el-button @click="cancel">{{ $t("formI18n.all.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      append-to-body
      width="400px"
    >
      <el-upload
        ref="uploadRef"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <el-icon :size="30">
          <ele-Upload />
        </el-icon>
        <div class="el-upload__text">{{ $t("system.userManagement.importText") }}</div>
        <template #tip>
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />
            {{ $t("system.userManagement.updateData") }}
            <el-link
              type="primary"
              @click="handleImportTemplate"
            >
              {{ $t("system.userManagement.downloadTemplate") }}
            </el-link>
          </div>
          <div
            class="el-upload__tip"
            style="color: red"
          >
            {{ $t("system.userManagement.uploadTip") }}
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitFileForm"
          >
            {{ $t("formI18n.all.confirm") }}
          </el-button>
          <el-button @click="upload.open = false">{{ $t("formI18n.all.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>

    <sync-cp-wx ref="syncCpWxRef" />
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import type { UploadInstance } from "element-plus";
import { ElMessageBox, ElTree, FormInstance } from "element-plus";
import {
  addUser,
  changeUserStatus,
  delUser,
  exportUser,
  getUser,
  importTemplate,
  pageUser,
  resetUserPwd,
  updateUser
} from "@/api/system/user";
import { baseUrl, getToken } from "@/utils/auth";
import { queryDeptInPost, treeselect } from "@/api/system/dept";
import { i18n } from "@/i18n";
import { listRole } from "@/api/system/role";
import { addDateRange, download, parseTime, resetFormRef } from "@/utils/tduck";
import { MessageUtil } from "@/utils/messageUtil";
import { getDicts } from "@/api/system/dict/data";
import { getConfigValue } from "@/api/system/config";
import SyncCpWx from "./SyncCpWx.vue";
import UserAuthInfo from "./UserAuthInfo.vue";

const loading = ref(true);
const exportLoading = ref(false);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const userList = ref(null);
const title = ref("");
const deptOptions = ref<undefined | any[]>(undefined);
const open = ref(false);
const deptName = ref<undefined | string>(undefined);
const initPassword = ref<undefined | string>(undefined);
const dateRange = ref([]);
const statusOptions = ref<any[]>([]);
const sexOptions = ref<any[]>([]);
const postOptions = ref<any[]>([]);
const roleOptions = ref<any[]>([]);
const roleList = ref<any[]>([]);

const form = ref<any>({
  id: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  password: undefined,
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: "0",
  remark: undefined,
  postIds: [],
  roleIds: []
});

const defaultProps = {
  children: "children",
  label: "label"
};

const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  updateSupport: 0,
  headers: { Authorization: "Bearer " + getToken() },
  url: baseUrl + "/system/user/importData"
});

const queryParams = reactive({
  current: 1,
  size: 10,
  roleIds: undefined,
  nickName: undefined,
  userName: undefined,
  phonenumber: undefined,
  email: undefined,
  status: undefined,
  deptId: undefined
});

const columns = reactive([
  { key: 0, label: i18n.global.t("system.userManagement.userNumber"), visible: true },
  { key: 1, label: i18n.global.t("system.userManagement.userName"), visible: true },
  { key: 2, label: i18n.global.t("system.userManagement.nickName"), visible: true },
  { key: 3, label: i18n.global.t("system.userManagement.dept"), visible: true },
  { key: 4, label: i18n.global.t("system.userManagement.phoneNumber"), visible: true },
  { key: 5, label: i18n.global.t("system.userManagement.email"), visible: true },
  { key: 6, label: i18n.global.t("system.userManagement.status"), visible: true },
  { key: 7, label: i18n.global.t("system.userManagement.createTime"), visible: true },
  { key: 8, label: i18n.global.t("system.userManagement.wxMpAccount"), visible: true }
]);

const rules = reactive({
  userName: [
    {
      required: true,
      message: i18n.global.t("system.userManagement.userNameNotNull"),
      trigger: "blur"
    }
  ],
  nickName: [
    {
      required: true,
      message: i18n.global.t("system.userManagement.nickNameNotNull"),
      trigger: "blur"
    }
  ],
  password: [
    { required: true, message: i18n.global.t("system.userManagement.passwordPlaceholder"), trigger: "blur" },
    {
      min: 5,
      max: 20,
      message: i18n.global.t("system.userManagement.passwordRequired"),
      trigger: "blur"
    }
  ],
  email: [
    {
      type: "email",
      message: i18n.global.t("system.userManagement.emailAddress"),
      trigger: ["blur", "change"]
    }
  ],
  phonenumber: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: i18n.global.t("system.userManagement.phoneNumberRequired"),
      trigger: "blur"
    }
  ]
});

const treeRef = ref<InstanceType<typeof ElTree>>();

watch(deptName, val => {
  treeRef.value!.filter(val);
});

const getList = () => {
  loading.value = true;
  pageUser(addDateRange(queryParams, dateRange.value)).then(response => {
    userList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
};

const getTreeselect = () => {
  treeselect().then(response => {
    deptOptions.value = response.data;
  });
};

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const handleNodeClick = (data: any) => {
  queryParams.deptId = data.id;
  getList();
};

const handleStatusChange = (row: any) => {
  const text =
    row.status === "0" ? i18n.global.t("system.userManagement.enable") : i18n.global.t("system.userManagement.disable");
  ElMessageBox.confirm(
    i18n.global.t("system.userManagement.confirmUserAction") +
      text +
      row.userName +
      i18n.global.t("system.userManagement.confirmUser"),
    i18n.global.t("formI18n.all.waring"),
    {
      confirmButtonText: i18n.global.t("formI18n.all.confirm"),
      cancelButtonText: i18n.global.t("formI18n.all.cancel"),
      type: "warning"
    }
  )
    .then(() => {
      return changeUserStatus(row.id, row.status);
    })
    .then(() => {
      MessageUtil.success(text + i18n.global.t("formI18n.all.success"));
    })
    .catch(() => {
      row.status = row.status === "0" ? "1" : "0";
    });
};

const cancel = () => {
  open.value = false;
  reset();
};

onMounted(() => {
  getList();
  getTreeselect();
  listRole({}).then(res => {
    roleList.value = res.data;
  });
  getDicts("sys_normal_disable").then((response: any) => {
    statusOptions.value = response.data;
  });
  getDicts("sys_user_sex").then(response => {
    sexOptions.value = response.data;
  });
  getConfigValue("sys.user.initPassword").then(response => {
    initPassword.value = response.data;
  });
});
const formRef = ref<FormInstance>();

const queryFormRef = ref<FormInstance>();

const reset = () => {
  form.value = {
    id: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: []
  };
  resetFormRef(formRef);
};

const handleQuery = () => {
  queryParams.current = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = [];
  resetFormRef(queryFormRef);
  handleQuery();
};

const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  getTreeselect();
  // 获取角色
  getUser().then(response => {
    roleOptions.value = response.data.roles;
    open.value = true;
    title.value = i18n.global.t("system.userManagement.addUser");
    nextTick(() => {
      reset();
      form.value!.password = initPassword.value;
    });
  });
};

const handleUpdate = (row: any) => {
  getTreeselect();
  const userId = row.id || ids.value;
  getUser(userId).then(async response => {
    open.value = true;
    title.value = i18n.global.t("system.userManagement.updateUser");
    await nextTick(async () => {
      reset();
      form.value = response.data.user;
      await getPostList();
      roleOptions.value = response.data.roles;
      form.value.postIds = response.data.postIds;
      form.value.roleIds = response.data.roleIds;
    });

    form.value!.password = undefined;
  });
};

const handleDeptChange = () => {
  getPostList().then(() => {
    form.value.postIds = [];
  });
};

const getPostList = async () => {
  const response = await queryDeptInPost({ deptId: form.value.deptId });
  postOptions.value = response.data;
};

// 重置密码按钮操作
const handleResetPwd = (row: any) => {
  ElMessageBox.prompt(
    i18n.global.t("formI18n.all.pleaseEnter") + row.userName + i18n.global.t("system.userManagement.newPassword"),
    i18n.global.t("formI18n.all.waring"),
    {
      confirmButtonText: i18n.global.t("formI18n.all.confirm"),
      cancelButtonText: i18n.global.t("formI18n.all.cancel"),
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: i18n.global.t("system.userManagement.passwordRequired")
    }
  )
    .then(({ value }) => {
      resetUserPwd(row.id, value).then(() => {
        MessageUtil.success(i18n.global.t("system.userManagement.resetPasswordSuccess") + value);
      });
    })
    .catch(() => {});
};

const router = useRouter();

// 分配角色操作
const handleAuthRole = (row: any) => {
  const userId = row.id;
  router.push("/auth/role/" + userId);
};

// 提交按钮
const submitForm = () => {
  formRef.value!.validate((valid: boolean) => {
    if (valid) {
      if (form.value.id !== undefined) {
        delete form.value.password;
        updateUser(form.value).then(() => {
          MessageUtil.success(i18n.global.t("formI18n.all.success"));
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then(() => {
          MessageUtil.success(i18n.global.t("formI18n.all.success"));
          getList();
          open.value = false;
        });
      }
    }
  });
};

// 删除按钮操作
const handleDelete = (row: any) => {
  const userIds = row.id || ids.value; // Replace with appropriate ID selection logic
  ElMessageBox.confirm(i18n.global.t("system.userManagement.confirmDelete"), i18n.global.t("formI18n.all.waring"), {
    confirmButtonText: i18n.global.t("formI18n.all.confirm"),
    cancelButtonText: i18n.global.t("formI18n.all.cancel"),
    type: "warning"
  })
    .then(() => delUser(userIds))
    .then(() => {
      MessageUtil.success(i18n.global.t("formI18n.all.success"));
      getList();
    })
    .catch(() => {});
};

// 导出按钮操作
const handleExport = () => {
  ElMessageBox.confirm(i18n.global.t("system.userManagement.confirmExport"), i18n.global.t("formI18n.all.waring"), {
    confirmButtonText: i18n.global.t("formI18n.all.confirm"),
    cancelButtonText: i18n.global.t("formI18n.all.cancel"),
    type: "warning"
  })
    .then(() => {
      exportLoading.value = true;
      return exportUser(queryParams);
    })
    .then(response => {
      download(response, i18n.global.t("system.userManagement.userData"));
      exportLoading.value = false;
    })
    .catch(() => {});
};

// 导入按钮操作
const handleImport = () => {
  upload.title = i18n.global.t("system.userManagement.importUser");
  upload.open = true;
};

// 下载模板操作
const handleImportTemplate = () => {
  importTemplate().then(response => {
    download(response, i18n.global.t("system.userManagement.importUserTemplate"));
  });
};

// 文件上传中处理
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

const uploadRef = ref<UploadInstance>();

// 文件上传成功处理
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value!.clearFiles();
  ElMessageBox.alert(response.msg, i18n.global.t("system.userManagement.importResult"), { dangerouslyUseHTMLString: true });
  getList();
};

// 提交上传文件
const submitFileForm = () => {
  uploadRef.value!.submit();
};
</script>
